package com.hfzy.ihk.web.freeswitchCall.biz;

import com.alibaba.fastjson.JSON;
import com.hfzy.ihk.facade.freeswitchCall.service.FreeswitchCallUpdateCallHistoryService;
import com.hfzy.ihk.web.freeswitchCall.constant.RedisKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 呼叫完成，将数据推送到hbase,主要是录音
 */
@Component
@Slf4j
public class PushDataToHbaseBiz {


    @Autowired
    RedisTemplate redisTemplate;

    @Autowired(required = false)
    private FreeswitchCallUpdateCallHistoryService freeswitchCallUpdateCallHistoryService;

    @Async("pushDataToHbaseTaskExecutor")
    public void pushDataToHbase(final Map<String, String> callHistoryMap){
        String data = "";
        if (callHistoryMap != null) {
            data = JSON.toJSONString(callHistoryMap);
        }else{
            log.info(">>>>>>>>..推送hbase数据为空，无法推送！");
            return;
        }

        try {
            log.info(">>>>>>>>开始将呼叫数据推送给hbase:{}", data);
            String rs = freeswitchCallUpdateCallHistoryService.upsertCallHistory(data);
            log.info(">>>>>>>>推送hbase完成 rs:{}", rs);
            if (rs.equals("1")) {
                log.info(">>>>>>>>推送hbase成功,sessionId：{}", String.valueOf(callHistoryMap.get("sessionId")));
            } else {
                log.info(">>>>>>>>推送hbases更新失败,sessionId：{}", String.valueOf(callHistoryMap.get("sessionId")));
                //放入redis 需要进行重推操作
                setReids(String.valueOf(callHistoryMap.get("sessionId")));
            }

        }catch (Exception e){
            log.error(">>>>>>>>>..推送记录到hbase失败data:{}",callHistoryMap.toString(),e);
            //放入redis 需要进行重推操作
            setReids(String.valueOf(callHistoryMap.get("sessionId")));
        }

    }

    /**
     * 将推送失败数据存入redis
     *
     * @param sessionId
     */
    public void setReids(String sessionId){
        try {
            redisTemplate.opsForSet().add(RedisKey.PUSH_RECORD_TO_HBASE_FAILED_SET, sessionId);

            log.info(">>>>>>>>将推送hbase失败数据保存到redis成功！");
        }catch ( Exception e){
            log.error(">>>>>>>>将推送hbase失败数据保存到redis失败！",e);
        }
    }


    /**
     * 将推送失败数据存入redis
     *
     * @param sessionId
     */
    public void removeRedis(String sessionId){
        try {
            redisTemplate.opsForSet().remove(RedisKey.PUSH_RECORD_TO_HBASE_FAILED_SET, sessionId);
            log.info(">>>>>>>>将推送hbase失败数据的redisKey删除成功！");
        }catch ( Exception e){
            log.error(">>>>>>>>将推送hbase失败数据的redisKey删除失败！",e);
        }
    }
}
